<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webSocket</title>
</head>
<style>
    .red-text {
        color: red; /* 将文本颜色设置为红色 */
    }
</style>
<body>
<div id="app">
    用户：<input v-model="username" placeholder="输入用户名"/><br/>
    地址：<input v-model="ipAddress" placeholder="服务器地址"/><br/>
    <button @click="config">连接</button>
    连接状态：<label>{{connectionState}}</label><br/>
    <div v-for="(data,index) in messageData" :key="index" :class="{'red-text': data.startsWith('我：')}">{{data}}</div>
    <input v-model="sendMessage"/>
    <button @click="socketSend">发送</button>
</div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.13/vue.js"></script>
<script>
    let v = new Vue({
        el: "#app",
        data: {
            connectionState: '未连接',
            message: '无消息',
            sendMessage: '',
            socket: null,
            username: '',
            ipAddress: 'localhost:8085',
            messageData: [],
            //发送心跳间隔
            heartbeatInterval: 30000
        },
        methods: {
            config() {
                if (this.connectionState === "未连接") {
                    this.socket = new WebSocket("ws://" + this.ipAddress + "/server/" + this.username);
                    this.socket.onopen = (event) => {
                        this.connectionState = "WebSocket 连接已建立";
                        setInterval(this.sendHeartbeat, this.heartbeatInterval);
                    };
                    this.socket.onmessage = (event) => {
                        this.messageData.push(event.data);
                    };
                }
            },
            // 发送心跳消息
            sendHeartbeat() {
                if (this.socket.readyState === WebSocket.OPEN) {
                    // 这里的心跳消息可以是一个简单的字符串
                    this.socket.send('heartbeat');
                }
            },
            socketSend() {
                if (this.socket && this.socket.readyState === WebSocket.OPEN) {
                    let mySelfMsg = "我：" + this.sendMessage
                    this.messageData.push(mySelfMsg);
                    this.socket.send(this.sendMessage);
                }
            },
        }
    })
</script>

</html>
